package com.lv.common.dialog.manager

import androidx.annotation.NonNull
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner

/**
 * 作者： ygx
 * 创建日期：2023/2/15 10:07 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：弹窗链拥有者，用于控制链节点的添加、移除、展示以及取消，销毁
 */

class DialogChainOwner(@NonNull owner: LifecycleOwner) : LifecycleEventObserver {
    private val chainNodes: MutableList<ChainNode> = ArrayList() //链节点列表
    private var cancelledIds //取消执行的链节点集合
            : MutableSet<Int>? = null
    var isDestroyed = false //是否销毁
        private set

    init {
        owner.getLifecycle().addObserver(this)
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        if (event === Lifecycle.Event.ON_DESTROY) {
            destroy()
        }
    }

    /**
     * 加入链节点
     *
     * @param chainNode
     * @return
     */
    fun join(chainNode: ChainNode): DialogChainOwner {
        chainNodes.add(chainNode)
        return this
    }

    /**
     * 移除链节点
     *
     * @param chainNode
     * @return
     */
    fun remove(chainNode: ChainNode): DialogChainOwner {
        chainNodes.remove(chainNode)
        return this
    }

    //开始展示
    fun show() {
        val chain = DialogChain(this, chainNodes, 0)
        chain.proceed()
    }

    //销毁
    fun destroy() {
        isDestroyed = true
        chainNodes.clear()
        if (cancelledIds != null) {
            cancelledIds!!.clear()
        }
    }

    /**
     * 取消链节点
     *
     * @param id
     */
    fun cancel(id: Int) {
        if (cancelledIds == null) {
            cancelledIds = HashSet()
        }
        cancelledIds!!.add(id)
    }

    fun isCancelled(id: Int): Boolean {
        return cancelledIds != null && cancelledIds!!.contains(id)
    }


}
